<?php

class wgEssentialRouting
{

  public static function listenToRoutingLoadConfigurationEvent( sfEvent $event )
  {
    $routing = $event->getSubject();
    $routing->appendRoute( 'essentialpage', new sfDoctrineRoute(
      '/*/:slug',
      array( 'module' => 'wgessentialpage', 'action' => 'index' ),
      array(),
      array( 'model' => 'EssentialPage', 'type' => 'object' )
    ));
  }
  
  public static function matches( $url, $node )
  {
    //sfContext::getInstance()->getLogger()->warning( $url );
    $segments = self::parseUrlSegments( $url );
    $ancestors = $node->getAncestors();
    if ( $ancestors )
    {
      for ( $it = 1 ; $it < count( $ancestors ) ; $it++ )
      {
        //sfContext::getInstance()->getLogger()->warning( $ancestors[$it]->getSlug() );
        if ( $segments[$it-1] != $ancestors[$it]->getSlug() ) return false;
      }
      if ( $it != count( $segments ) ) return false;
    }
    //else sfContext::getInstance()->getLogger()->warning( 'no ancestors!' );
    return true;
  }

  protected static function parseUrlSegments( $url )
  {
    $segments = array();
    foreach ( explode( '/', $url ) as $segment )
    {
      if ( $segment ) $segments[] = $segment;
    }
    return $segments;
  }

}
